package site.fantasycube.blog.util.exception;

import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import site.fantasycube.blog.util.result.Fail;

import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.List;

/*
 *描述 全局异常捕捉
 * @author huanan&huanyue
 * @Date 2021/10/28
 */
@RestControllerAdvice
public class GlobEcxeption {

    /*
     *描述： 空指针异常捕捉
     * @Author huanan&huanyue
     * @Date 2021/10/28 9:51
     * @Param
     * @return
     **/
    @ExceptionHandler(NullPointerException.class)
    public Fail nullPointExceptionHandler(NullPointerException e){
        e.printStackTrace();
        return Fail.me(500,"参数异常:"+e.getMessage());
    }

    /*
     *描述： 算术异常捕捉
     * @Author huanan&huanyue
     * @Date 2021/10/28 9:51
     * @Param
     * @return
     **/
    @ExceptionHandler(ArithmeticException.class)
    public Fail arithmeticExceptionHandler(ArithmeticException e){
        e.printStackTrace();
        return Fail.me(500,"算术异常:"+e.getMessage());
    }

    /*
     *描述： 业务异常捕捉
     * @Author huanan&huanyue
     * @Date 2021/10/28 9:51
     * @Param
     * @return
     **/
    @ExceptionHandler(site.fantasycube.blog.util.exception.BlogException.class)
    public Fail hrmExceptionHandler(BlogException e){
        e.printStackTrace();
        return Fail.me(406,e.getMessage());
    }
    @ExceptionHandler(SocketTimeoutException.class)
    public Fail SocketTimeoutException(SocketTimeoutException e){
        e.printStackTrace();
        return Fail.me(500,"网关异常:"+e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Fail manveExceptionHandler(MethodArgumentNotValidException e){

        HashMap<String, Object> map = new HashMap<>();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        for (ObjectError allError : allErrors) {
            map.put(allError.getObjectName().toString(),allError.getDefaultMessage());
        }
        e.printStackTrace();
        return Fail.me(500,"后台异常:"+map.toString());
    }
}
